package cn.itcast.nems.manager.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChineseCharacterUtil {
    private static String regExp = "^[\u4E00-\u9FFF]+$";

    /**
     * 将行字转换为拼音, 以'_'分隔, 并忽略特殊字符
     *
     * @param word 汉字
     * @return java.lang.String 拼音
     * @author 高昌露
     * @since 2023/11/23 10:20
     */
    public static String toPinyinIgnoreSpecialCharacters(@NotNull String word) {
        return toPinyin(word, Boolean.TRUE);
    }

        /***
         * 将单个汉字转成拼音
         * @param word 文本
         * @return 拼音字符串
         */
    public static String toPinyin(@NotNull String word, boolean ignoreSpecialCharacters) {
        char[] chars = word.toCharArray();
        List<String> list = new ArrayList<>();
        StringBuilder other  =  new StringBuilder( );
        for (char aChar : chars) {
            if (!match(String.valueOf(aChar), regExp)) {
                other.append(aChar);
                continue;
            }
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(aChar);
            if (Objects.nonNull(pinyinArray) && pinyinArray.length > 0) {
                list.add(pinyinArray[0].substring(0, pinyinArray[0].length() - 1));
            }
        }
        if(!ignoreSpecialCharacters && !other.isEmpty()) {
            list.add(String.valueOf(other)) ;
        }
        return String.join("_", list).toUpperCase();
    }

    /***
     * @param str 源字符串
     * @param regex 正则表达式
     * @return 是否匹配
     */
    public static boolean match(String str, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }
}